package net.davidlauzon.assemblandroid.activities;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import net.davidlauzon.assemblandroid.R;
import net.davidlauzon.assemblandroid.TicketListAdapter;
import net.davidlauzon.assemblandroid.TimeTrackerApplication;
import net.davidlauzon.assemblandroid.exceptions.XMLParsingException;
import net.davidlauzon.assemblandroid.models.Ticket;
import net.davidlauzon.utils.IObserver;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class TicketListingActivity extends Activity implements IObserver {
	static private final String TAG = "AssemblaTT";
	
	// GRASP Controller
	private TimeTrackerApplication app;

	private ProgressDialog loadingDialog;

	private ListView listView;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "TicketListingActivity.onCreate()");
        
        setContentView(R.layout.ticket_list);
        
        listView = (ListView)findViewById(R.id.ticketListView);
        
        app = TimeTrackerApplication.getInstance();
        
        loadTickets();
    }
    
    private void loadTickets() {
    	loadTickets(false);
    }
    
    private void loadTickets(boolean forceReload) {
    	if (forceReload || !app.ticketsReady()) {
    		//Log.i(TAG, "tickets not there : NEED TO LOAD TICKETS");
    		// Delay loading of records to avoid blocking the UI
	    	// Note: onUpdate() will be called when the task completes
	        loadingDialog = ProgressDialog.show(this, "", "Loading tickets. Please wait...", true);
	        app.fetchTicketsLater( this );
    	} else {
    		// Log.i(TAG, "tickets already there");
    		// If records were already loaded, use the existing data
    		onUpdate();
    	}
    }

    
    /**
     * Called when tickets are ready
     */
	public void onUpdate() {
		Log.i(TAG, "TicketListingActivity::onUpdate");
		
		if (app.ticketsReady()) {
			//ArrayList<String> names = app.ticketNamesForList();
			ArrayList<Ticket> tickets;
			try {
				tickets = app.ticketsForList();
			} catch (XMLParsingException e) {
				Log.e(TAG, e.toString());
				e.printStackTrace();
				tickets = new ArrayList<Ticket>();
			}
			
			// create the grid item mapping
	        String[] from = new String[] {"A", "B", "C"};
	        int[] to = new int[] { R.id.item1, R.id.item2, R.id.item3};

	        // prepare the list of all records
	        ArrayList<HashMap<String, String>> items = new ArrayList<HashMap<String, String>>();
	        
	        for(Ticket t : tickets) {
	        	HashMap<String, String> hash = new HashMap<String, String>();
	        	hash.put("A", Integer.toString(t.priority()) );
	        	hash.put("B", t.name());
	        	hash.put("C", String.format("%s / %s", t.workedHoursHuman(), t.workingHoursHuman()) );
	        	
	        	items.add(hash);
	        }
			
	    	TicketListAdapter adapter = new TicketListAdapter(this, items, R.layout.ticket_list_item, from, to);
	    	
	    	listView.setAdapter(adapter);

	    	listView.setOnItemClickListener( new OnItemClickListener() {
	        	public void onItemClick( AdapterView<?> parent, View view, int position, long id ) {
	        		// When clicked, show a toast with the TextView text
	        		//Log.i(TAG, "OnItemClickListener :: Position:" + Integer.toString(position) + " / id:" + Long.toString(id) + " / " + allTickets.get(position).toString());
	        		
	        		try {
						app.selectTicket( position );
						
						// Launch another activity
		                Intent myIntent = new Intent(TicketListingActivity.this, TicketDetailsActivity.class);
		                TicketListingActivity.this.startActivity(myIntent);
		                
					} catch (XMLParsingException e) {
						Log.e(TAG, e.toString());
						e.printStackTrace();
					}
	        	}
	        });
	        
			/*
			setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, names ));
	
	        ListView lv = getListView();
	        lv.setTextFilterEnabled(true);
	        
	        //lv.getItemAtPosition(0);
	
	        lv.setOnItemClickListener( new OnItemClickListener() {
	        	public void onItemClick( AdapterView<?> parent, View view, int position, long id ) {
	        		// When clicked, show a toast with the TextView text
	        		//Log.i(TAG, "OnItemClickListener :: Position:" + Integer.toString(position) + " / id:" + Long.toString(id) + " / " + allTickets.get(position).toString());
	        		
	        		app.selectTicket( position );
	        		
	        		// Launch another activity
	                Intent myIntent = new Intent(TicketListingActivity.this, TicketDetailsActivity.class);
	                TicketListingActivity.this.startActivity(myIntent);
	        	}
	        });
	        */
	        
	        if (loadingDialog != null) {
	        	loadingDialog.cancel();
	        	loadingDialog = null;
	        }
		}
	}

	
	/**
	 * Called when the options button (bottom left) is pressed
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		Log.i(TAG, "onCreateOptionsMenu");
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.tickets_listing_activity, menu);
		return true;
	}

	// This method is called once the menu is selected
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.i(TAG, "onOptionsItemSelected");
		
		switch (item.getItemId()) {
			case R.id.preferences:
				// Launch Preference activity
				startActivity( new Intent(this, EditPreferencesActivity.class) );
				// Some feedback to the user
				Toast.makeText(this, "Here you can maintain your user credentials.", Toast.LENGTH_SHORT).show();
				break;
			
			case R.id.reload:
				loadTickets(true);
				break;
		}
		return true;
	}
    
    /**
     * @see http://stackoverflow.com/questions/456211/activity-restart-on-rotation-android
     * 
     * Called by the system when the device configuration changes while your activity is running. 
     * 
     * Note that this will only be called if you have selected configurations you would like to 
     * handle with the configChanges attribute in your manifest. If any configuration change 
     * occurs that is not selected to be reported by that attribute, then instead of reporting it 
     * the system will stop and restart the activity (to have it launched with the new 
     * configuration).
     * 
     * At the time that this function has been called, your Resources object will have been 
     * updated to return resource values matching the new configuration.
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    	super.onConfigurationChanged(newConfig);
    	Log.i(TAG, "TicketsListingActivity::onConfigurationChanged()");
    }
    
    
    /**
     * Called just before the activity starts interacting with the user. 
     * 
     * At this point the activity is at the top of the activity stack, with user input going to it.
     * 
     * Always followed by onPause().
     */
    @Override
    public void onResume() {
    	super.onResume();
        Log.i(TAG, "TicketListingActivity::onResume()");
        
        onUpdate();
    }
}